package GUI;

import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.*;

import database.TableManager;
import database.TableManager.TableEnum;

import amsStore.*;
import item.*;

import java.sql.Date;

////////////////////
// Basic procedure of our UI is to create all the panels on init and then add/remove
//  them from the main frame as the user hits forward/back/transaction buttons etc...
////////////////////
public class GUI_AMSStoreMain extends JFrame implements ActionListener, KeyListener {

	boolean startingUp = true;
	
	private TableManager tm = null;
	
	JMenuBar navBar; // see navBarButtons
	ArrayList navBarButtons = new ArrayList(); // used on top bar to show current menu page
	ArrayList navBarArrows = new ArrayList(); // goes between each button for visual
	
	// make each GUI panel (see other classes in GUI package for details):
	GUI_page01_UserSelection page01_userSelection = new GUI_page01_UserSelection();
	GUI_page02_Clerk page02_clerk = new GUI_page02_Clerk();	
	GUI_page02_ProcessPurchase page02_processPurchase = new GUI_page02_ProcessPurchase();
	GUI_page02_ProcessReturn page02_processReturn = new GUI_page02_ProcessReturn();
	GUI_page03_Customer page03_customer = new GUI_page03_Customer();
	GUI_page03_CustomerLogin page03_customerLogin = new GUI_page03_CustomerLogin();
	GUI_page03_CustomerRegister page03_customerRegister = new GUI_page03_CustomerRegister();
	GUI_page03_Shopping page03_shopping = new GUI_page03_Shopping();
	GUI_page03_Checkout page03_checkout = new GUI_page03_Checkout();
	GUI_page04_Manager page04_manager = new GUI_page04_Manager();
	GUI_page04_AddSupplier page04_addSupplier = new GUI_page04_AddSupplier();
	GUI_page04_RemoveSupplier page04_removeSupplier = new GUI_page04_RemoveSupplier();
	GUI_page04_ProcessShipment page04_processShipment = new GUI_page04_ProcessShipment();
	GUI_page04_ProcessOrders page04_processOrders = new GUI_page04_ProcessOrders();
	GUI_page04_DailySalesReport page04_dailySalesReport = new GUI_page04_DailySalesReport();
	GUI_page04_TopSellingItems page04_topSellingItems = new GUI_page04_TopSellingItems();
	GUI_page05_Admin page05_admin = new GUI_page05_Admin();
	GUI_page05_InsertToTable page05_insertToTable = new GUI_page05_InsertToTable();
	GUI_page05_DeleteFromTable page05_deleteFromTable = new GUI_page05_DeleteFromTable();
	GUI_page05_DisplayTables page05_displayTables = new GUI_page05_DisplayTables();
	
	public GUI_AMSStoreMain()
	{
		// title and setup
		this.setTitle("AMS Store - The leader in AMS stores worldwide");
		this.setLocation(10,10);
		this.setSize(900, 600);
		this.setMinimumSize(new Dimension(900,600)); // size is locked due to centering panels issues
		this.setMaximumSize(new Dimension(900,600));
		this.setResizable(false);
		getContentPane().setBackground(Color.white);
		this.setLocationRelativeTo(null); // centers the entire applet
		
		// menu bar (initially empty) - used to track where you are in the UI hierarchy (navigation bar essentially)
		navBar = new JMenuBar();
		this.setJMenuBar(navBar);
		JLabel navBarDescripLab = new JLabel(" Navigation Bar ", JLabel.CENTER);
		navBarDescripLab.setFont(new Font("Century Gothic", Font.PLAIN, 14));
		navBarDescripLab.setForeground(Color.gray);
        navBar.add(navBarDescripLab);

		///////////////////////////////////////////////////////////////////
		// REGISTER EACH PAGE's ACTIONS TO THIS MAIN CLASS
		page01_userSelection.continueButton.addActionListener(this);
		//--
		page02_clerk.returnButton.addActionListener(this);
		page02_clerk.processPurchaseButton.addActionListener(this);
		page02_clerk.processReturnButton.addActionListener(this);
		//--
		page02_processPurchase.returnButton.addActionListener(this);
		page02_processPurchase.paymentTypeList.addActionListener(this);
		page02_processPurchase.UPCField.addKeyListener(this);
		page02_processPurchase.addItemButton.addActionListener(this);
		page02_processPurchase.removeItemButton.addActionListener(this);
		page02_processPurchase.processAndSaveButton.addActionListener(this);
		//--
		page02_processReturn.returnButton.addActionListener(this);
		page02_processReturn.receiptIDField.addKeyListener(this);
		page02_processReturn.itemUPCField.addKeyListener(this);
		page02_processReturn.returnItemButton.addActionListener(this);
		//--
		page03_customer.returnButton.addActionListener(this);
		page03_customer.loginButton.addActionListener(this);
		page03_customer.registerButton.addActionListener(this);
		//--
		page03_customerLogin.returnButton.addActionListener(this);
		page03_customerLogin.loginButton.addActionListener(this);
		//--
		page03_customerRegister.returnButton.addActionListener(this);
		page03_customerRegister.saveButton.addActionListener(this);
		//--
		page03_shopping.logoutButton.addActionListener(this);
		page03_shopping.categoryList.addActionListener(this);
		page03_shopping.categoryList.setSelectedIndex(0);
		page03_shopping.itemTitleField.addKeyListener(this);
		page03_shopping.leadSingerField.addKeyListener(this);
		page03_shopping.addToCartButton.addActionListener(this);
		page03_shopping.removeItemButton.addActionListener(this);
		page03_shopping.checkoutButton.addActionListener(this);
		//--
		page03_checkout.returnButton.addActionListener(this);
		page03_checkout.confirmButton.addActionListener(this);
		//--
		page04_manager.returnButton.addActionListener(this);
		page04_manager.addSupplierButton.addActionListener(this);
		page04_manager.removeSupplierButton.addActionListener(this);
		page04_manager.processShipmentButton.addActionListener(this);
		page04_manager.processOrderButton.addActionListener(this);
		page04_manager.dailySalesReportButton.addActionListener(this);
		page04_manager.topSellingItemsButton.addActionListener(this);
		//--
		page04_addSupplier.returnButton.addActionListener(this);
		page04_addSupplier.submitButton.addActionListener(this);
		//--
		page04_removeSupplier.returnButton.addActionListener(this);
		page04_removeSupplier.supplierNameField.addKeyListener(this);
		page04_removeSupplier.submitButton.addActionListener(this);
		//--
		page04_processShipment.returnButton.addActionListener(this);
		page04_processShipment.shipmentIDField.addKeyListener(this);
		page04_processShipment.processButton.addActionListener(this);
		//--
		page04_processOrders.returnButton.addActionListener(this);
		page04_processOrders.processButton.addActionListener(this);		
		//--
		page04_dailySalesReport.returnButton.addActionListener(this);
		page04_dailySalesReport.storeList.addActionListener(this);
		page04_dailySalesReport.dateField.addKeyListener(this);
		//--
		page04_topSellingItems.returnButton.addActionListener(this);
		page04_topSellingItems.submitButton.addActionListener(this);
		//--
		page05_admin.returnButton.addActionListener(this);
		page05_admin.createTablesButton.addActionListener(this);
		page05_admin.dropTablesButton.addActionListener(this);
		page05_admin.populateTablesButton.addActionListener(this);
		page05_admin.insertToTableButton.addActionListener(this);
		page05_admin.deleteFromTableButton.addActionListener(this);
		page05_admin.displayTableButton.addActionListener(this);
		//--
		page05_displayTables.returnButton.addActionListener(this);
		page05_displayTables.tableList.addActionListener(this);
		page05_displayTables.tableList.setSelectedIndex(0);
		//--
		page05_insertToTable.returnButton.addActionListener(this);
		page05_insertToTable.tableList.addActionListener(this);
		page05_insertToTable.tableList.setSelectedIndex(0);
		page05_insertToTable.insertButton.addActionListener(this);
		//--
		page05_deleteFromTable.returnButton.addActionListener(this);
		page05_deleteFromTable.tableList.addActionListener(this);
		page05_deleteFromTable.tableList.setSelectedIndex(0);
		page05_deleteFromTable.deleteButton.addActionListener(this);
		
		// show and start on user selection page (and make it centered)
		this.goToPage(true, "User Selection", null, new Dimension(0, 120), null, null, page01_userSelection, BorderLayout.CENTER);
	 
	    setDefaultCloseOperation(EXIT_ON_CLOSE);
	    this.setVisible(true);
	    
	    tm = TableManager.getInstance();
	    startingUp = false;
	}
	
	// this method contains every forward/back button action basically (and every transaction once they're connected...)
	// ... takes care of all of the logic for each page
	@Override
	public void actionPerformed(ActionEvent e) {
		if (startingUp)
			return;
// go to clerk page
		if ((e.getSource() == page01_userSelection.continueButton && page01_userSelection.userList.getSelectedIndex() == 0))
		{
			this.goToPage(true, "Clerk Menu", new Dimension(350,0), new Dimension(0, 125), null, null, page02_clerk, BorderLayout.CENTER);
			return;
		}
// go to customer page
		if ((e.getSource() == page01_userSelection.continueButton && page01_userSelection.userList.getSelectedIndex() == 1))
		{
			this.goToPage(true, "Customer Menu", new Dimension(350,0), new Dimension(0, 125), null, null, page03_customer, BorderLayout.CENTER);
			return;
		}
// go to manager page
		if ((e.getSource() == page01_userSelection.continueButton && page01_userSelection.userList.getSelectedIndex() == 2))
		{ 
			this.goToPage(true, "Manager Menu", new Dimension(350,0), new Dimension(0, 125), null, null, page04_manager, BorderLayout.CENTER);
			return;
		}
// go to admin page
		if ((e.getSource() == page01_userSelection.continueButton && page01_userSelection.userList.getSelectedIndex() == 3))
		{ 
			this.goToPage(true, "Admin Menu", new Dimension(350,0), new Dimension(0, 125), null, null, page05_admin, BorderLayout.CENTER);
			return;
		}
// go back to front page
		if (e.getSource() == page02_clerk.returnButton || e.getSource() == page03_customer.returnButton || e.getSource() == page05_admin.returnButton || e.getSource() == page04_manager.returnButton)
		{ 
			this.goToPage(false, "", null, new Dimension(0, 120), null, null, page01_userSelection, BorderLayout.CENTER);
			return;
		}
// go to Clerk's process purchase page
		if (e.getSource() == page02_clerk.processPurchaseButton)
		{ 
			try {
				page02_processPurchase.storeOptions = tm.clerkGetStoreNames();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			page02_processPurchase.resetPage();
			this.goToPage(true, "Process Purchase", new Dimension(150, 0), new Dimension(0, 75), new Dimension(125, 0), new Dimension(0, 0), page02_processPurchase, BorderLayout.CENTER);
			return;
		}
// go to clerk process return page
		if (e.getSource() == page02_clerk.processReturnButton)
		{
			try {
				page02_processReturn.storeOptions = tm.clerkGetStoreNames();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			page02_processReturn.resetPage();
			this.goToPage(true, "Process Return", new Dimension(350,0), new Dimension(0, 125), null, null, page02_processReturn, BorderLayout.CENTER);
			return;
		}
// go back to clerk page
		if (e.getSource() == page02_processPurchase.returnButton || e.getSource() == page02_processReturn.returnButton)
		{ 
			this.goToPage(false, "", new Dimension(350,0), new Dimension(0, 125), null, null, page02_clerk, BorderLayout.CENTER);
			return;
		}
// update payment type on clerk's process purchase
		if (e.getSource() == page02_processPurchase.paymentTypeList)
		{ 
			// to cash
			if (page02_processPurchase.paymentTypeList.getSelectedIndex() == 0)
			{
				page02_processPurchase.paymentCCNPane.setVisible(false);
				page02_processPurchase.paymentCCExpPane.setVisible(false);
			}
			// to credit card
			else
			{
				page02_processPurchase.paymentCCNPane.setVisible(true);
				page02_processPurchase.paymentCCExpPane.setVisible(true);
			}
			return;
		}
// add a new shopping cart item and update jlist
		if (e.getSource() == page02_processPurchase.addItemButton)
		{ 
			if (page02_processPurchase.foundItemLabel.getText().equals("")) // no item exists
				return;
			String UPCText = (String) page02_processPurchase.UPCField.getText();
			String quantityText = (String) page02_processPurchase.quantityField.getText();
			int quantity;
		    try
		    {
		      quantity = Integer.parseInt(quantityText.trim());
		    }
		    catch (NumberFormatException nfe)
		    {
		    	JOptionPane.showMessageDialog(this, nfe.getMessage());
		    	return;
		    }
			
			ShoppingCartItem theItem;
			try {
				theItem = tm.clerkGetShoppingCartItem(UPCText, quantity);
			} catch (SQLException e1) {
				theItem = null;
				JOptionPane.showMessageDialog(this, e1.getMessage());
			}
			
			if (theItem != null)
			{
				if (page02_processPurchase.shoppingJList.getSelectedValue().toString().equals("Empty")) // check empty item
					page02_processPurchase.listModel.remove(0);
				page02_processPurchase.shoppingList.add(theItem);
				page02_processPurchase.listModel.addElement(theItem.getTitle());
				page02_processPurchase.processAndSaveButton.setEnabled(true);
				page02_processPurchase.removeItemButton.setEnabled(true);
				if (page02_processPurchase.listModel.getSize() == 1)
					page02_processPurchase.shoppingJList.setSelectedIndex(0);
			}
			
			return;
		}
// if clerk has a selection, remove item from shopping list (as long as list has > 0 elements) and update jlist
		if (e.getSource() == page02_processPurchase.removeItemButton)
		{ 
			int index = page02_processPurchase.shoppingJList.getSelectedIndex();
			if (index == -1)
				return;

			page02_processPurchase.listModel.remove(index);
			page02_processPurchase.shoppingList.remove(index);

		    int size = page02_processPurchase.listModel.getSize();

		    if (size == 0)
		    { // empty list
		    	page02_processPurchase.removeItemButton.setEnabled(false);
		    	page02_processPurchase.processAndSaveButton.setEnabled(false);
		    	page02_processPurchase.listModel.addElement("Empty");
		    	page02_processPurchase.shoppingJList.setSelectedIndex(0);

		    }
		    else
		    { //Select an index.
		        if (index == page02_processPurchase.listModel.getSize())
		        {
		            //removed item in last position
		            index--;
		        }
		        page02_processPurchase.shoppingJList.setSelectedIndex(index);
		        page02_processPurchase.shoppingJList.ensureIndexIsVisible(index);
		    }
		    return;
		}
// transact shopping items from clerk process purchase page
		if (e.getSource() == page02_processPurchase.processAndSaveButton)
		{ 		
			try
			{
				String purchaseDateString = page02_processPurchase.dateField.getText(); // purchase date
				Date purchaseDate = Date.valueOf(purchaseDateString);
			
				Boolean creditPur = true;
				if (page02_processPurchase.paymentTypeList.getSelectedIndex() == 0) // cash or credit purchase
					creditPur = false;
				String expiryDateString;
				Date expireDate = null;
				if (creditPur)
				{
					expiryDateString = page02_processPurchase.creditCardExpiryField.getText(); // credit card date
					expireDate = Date.valueOf(expiryDateString);
				}
				Receipt tempReceipt;
				
				tempReceipt = tm.clerkProcessPurchase(page02_processPurchase.shoppingList, page02_processPurchase.storeList.getSelectedItem().toString(), purchaseDate, creditPur, page02_processPurchase.creditCardNumberField.getText(), expireDate);
				
				// text receipt for now
				System.out.println(page02_processPurchase.storeList.getSelectedItem().toString() + " purchase");
				System.out.println(purchaseDateString);
				System.out.println();
				for (int i = 0; i < page02_processPurchase.listModel.getSize(); i++)
				{
					System.out.println(page02_processPurchase.listModel.get(i));
				}
				if (tempReceipt.isCreditPurchase())
					System.out.println("Card " + tempReceipt.getCardLastFiveDigits());
				System.out.println("Total Amount: " + tempReceipt.getTotalPurchaseAmount());
				JOptionPane.showMessageDialog(this, "Purchase Successful!");
				this.actionPerformed(new ActionEvent(page02_processPurchase.returnButton, getDefaultCloseOperation(), ""));			
			}
			catch(IllegalArgumentException e1)
			{
				JOptionPane.showMessageDialog(this, "Invalid date format");
			}
			catch (Exception e1) {
			
				JOptionPane.showMessageDialog(this, e1.getMessage());
			}
			return;
		}
// confirm a returning of an item
		if (e.getSource() == page02_processReturn.returnItemButton)
		{
			java.util.Date today = new java.util.Date();
			java.sql.Date sqlToday = new java.sql.Date(today.getTime()); // current date
			String quantityText = (String) page02_processReturn.amountField.getText();
			int quantity;
		    try
		    {
		      quantity = Integer.parseInt(quantityText.trim());
		    }
		    catch (NumberFormatException nfe)
		    {
		    	JOptionPane.showMessageDialog(this, nfe.getMessage());
		    	return;
		    }
		    float refundAmount;
			try {
				refundAmount = tm.clerkProcessReturnFromReceiptId(page02_processReturn.receiptIDField.getText(), sqlToday, page02_processReturn.storeList.getSelectedItem().toString(), page02_processReturn.itemUPCField.getText(), quantity);
			} catch (Exception e1) {
				JOptionPane.showMessageDialog(this, e1.getMessage());
				return;
			}
			JOptionPane.showMessageDialog(this, "Return Successful, you have been credited $" + refundAmount);
			return;
		}
// go to customer login page
		if (e.getSource() == page03_customer.loginButton)
		{
			this.goToPage(true, "Customer Login", new Dimension(340, 0), new Dimension(0, 130), new Dimension(75, 0), new Dimension(0, 75), page03_customerLogin, BorderLayout.CENTER);
			return;
		}
// go to customer register page
		if (e.getSource() == page03_customer.registerButton)
		{ 
			this.goToPage(true, "Customer Register", new Dimension(340, 0), new Dimension(0, 120), new Dimension(75, 0), new Dimension(0, 75), page03_customerRegister, BorderLayout.CENTER);
			return;
		}
// go back to customer page
		if (e.getSource() == page03_customerLogin.returnButton || e.getSource() == page03_customerRegister.returnButton)
		{ 
			this.goToPage(false, "", new Dimension(350,0), new Dimension(0, 125), null, null, page03_customer, BorderLayout.CENTER);
			return;
		}
// try and login for a user (and go to shopping), if fails display failure message on resultLabel of customerLogin page
		if (e.getSource() == page03_customerLogin.loginButton)
		{ 
			tm = TableManager.getInstance();
			boolean loginResult = false;
			try {
				loginResult =  tm.customerLogin(page03_customerLogin.cidField.getText(), new String(page03_customerLogin.passField.getPassword()));
			} catch (Exception r) {
				//JOptionPane.showMessageDialog(this, r.getMessage());
				loginResult = false;
			}
			if (loginResult)
			{
				page03_customerLogin.resultLabel.setText("");
				this.goToPage(true, "Shopping Menu", new Dimension(125,0), new Dimension(0, 100), new Dimension(125,0), new Dimension(0, 100), page03_shopping, BorderLayout.CENTER);
				page03_shopping.cid = page03_customerLogin.cidField.getText();
				this.invalidate();
				page03_shopping.resetPage();
				this.searchItems(); // simulate first search of category
				this.validate();
				this.repaint();
				page03_shopping.cameFromLogin = true;
				this.actionPerformed(new ActionEvent(page03_shopping.categoryList, getDefaultCloseOperation(), ""));
			}
			else
			{
				page03_customerLogin.resultLabel.setText("Login failed");
			}
			
			return;
		}
// try and save a new user (and go to shopping), if fails display failure message on resultLabel of customerRegister page
		if (e.getSource() == page03_customerRegister.saveButton)
		{ 
			try {
				tm.customerRegistration(page03_customerRegister.cidField.getText(), new String(page03_customerRegister.passField.getPassword()), page03_customerRegister.nameField.getText(), page03_customerRegister.addressField.getText(), page03_customerRegister.phoneNumberField.getText());
			
				page03_customerRegister.resultLabel.setText("");
				this.goToPage(true, "Shopping Menu", new Dimension(125,0), new Dimension(0, 100), new Dimension(125,0), new Dimension(0, 100), page03_shopping, BorderLayout.CENTER);
				page03_shopping.cid = page03_customerRegister.cidField.getText();
				this.invalidate();
				page03_shopping.resetPage();				
				this.searchItems(); // simulate first search of category
				this.validate();
				this.repaint();
				page03_shopping.cameFromLogin = true; // changed because makes sense to go back here
				this.actionPerformed(new ActionEvent(page03_shopping.categoryList, getDefaultCloseOperation(), ""));
			
			} catch (Exception r) {
				JOptionPane.showMessageDialog(this, r.getMessage());		
				page03_customerRegister.resultLabel.setText("Registration failed");
			}			
			
			return;
		}
// logout but checks if going back to login or register
		if (e.getSource() == page03_shopping.logoutButton)
		{ 
			if (this.page03_shopping.cameFromLogin)
				this.goToPage(false, "", new Dimension(340, 0), new Dimension(0, 130), new Dimension(75, 0), new Dimension(0, 75), page03_customerLogin, BorderLayout.CENTER);
			else
				this.goToPage(false, "", new Dimension(340, 0), new Dimension(0, 120), new Dimension(75, 0), new Dimension(0, 75), page03_customerRegister, BorderLayout.CENTER);
			return;
		}
// update search from category list change
		if (e.getSource() == page03_shopping.categoryList)
		{ 
			this.searchItems();
		}
// add selection of shopping table (with quantity field's value as well) to shopping cart
		if (e.getSource() == page03_shopping.addToCartButton)
		{ 
			Integer selectedRow = page03_shopping.table.getSelectionModel().getMinSelectionIndex();
			String UPCText = (String) page03_shopping.table.getValueAt(selectedRow, 0); // gets UPC
			String quantityText = (String) page03_shopping.quantityField.getText();
			int quantity;
		    try
		    {
		      quantity = Integer.parseInt(quantityText.trim());
		    }
		    catch (NumberFormatException nfe)
		    {
		    	JOptionPane.showMessageDialog(this, nfe.getMessage());
		    	return;
		    }
		    Integer countAvailable;
		    try {
				countAvailable = tm.customerGetOnlineQuantityAvailable(UPCText);
			} catch (SQLException e2) {
				JOptionPane.showMessageDialog(this, e2.getMessage());
				return;
			}
			if (countAvailable == 0)
			{
				JOptionPane.showMessageDialog(this, "No stock available");
				return;
			}
			if (countAvailable < quantity)
			{
				JOptionPane.showMessageDialog(this, "Not enough stock for this amount");
				return;
			}
		    
			ShoppingCartItem theItem;
			try {
				theItem = tm.clerkGetShoppingCartItem(UPCText, quantity); // have to use clerk method for now
			} catch (SQLException e1) {
				theItem = null;
				JOptionPane.showMessageDialog(this, e1.getMessage());
			}
			
			if (theItem != null)
			{
				if (page03_shopping.shoppingCart.getSelectedValue().toString().equals("Empty")) // check empty item
					page03_shopping.listModel.remove(0);
				page03_shopping.shoppingList.add(theItem);
				page03_shopping.listModel.addElement(quantityText + " " + theItem.getTitle() + " @" + theItem.getSellPrice());
				page03_shopping.checkoutButton.setEnabled(true);
				page03_shopping.removeItemButton.setEnabled(true);
				if (page03_shopping.listModel.getSize() == 1)
					page03_shopping.shoppingCart.setSelectedIndex(0);
			}
			
			return;
		}
// take selection of shoppingCart and remove from shoppingList; if 0, add Empty and disable this button/checkout button
		if (e.getSource() == page03_shopping.removeItemButton)
		{ 
			int index = page03_shopping.shoppingCart.getSelectedIndex();
			if (index == -1)
				return;

			page03_shopping.listModel.remove(index);
			page03_shopping.shoppingList.remove(index);

		    int size = page03_shopping.listModel.getSize();

		    if (size == 0)
		    { // empty list
		    	page03_shopping.removeItemButton.setEnabled(false);
		    	page03_shopping.checkoutButton.setEnabled(false);
		    	page03_shopping.listModel.addElement("Empty");
		    	page03_shopping.shoppingCart.setSelectedIndex(0);
		    }
		    else
		    { //Select an index.
		        if (index == page03_shopping.listModel.getSize())
		        {
		            //removed item in last position
		            index--;
		        }
		        page03_shopping.shoppingCart.setSelectedIndex(index);
		        page03_shopping.shoppingCart.ensureIndexIsVisible(index);
		    }
		    return;
		}
// go to bill/checkout page, passing on the list
		if (e.getSource() == page03_shopping.checkoutButton)
		{
			this.goToPage(true, "Customer Checkout", new Dimension(150,0), new Dimension(0,75), new Dimension(150,0), new Dimension(0,75), page03_checkout, BorderLayout.CENTER);
			Bill theBill = new Bill(page03_shopping.shoppingList);
			this.invalidate();
			page03_checkout.resetPage(theBill);
			this.validate();
			this.repaint();
			return;
		}
// go back to shopping page
		if (e.getSource() == page03_checkout.returnButton)
		{ 
			this.goToPage(false, "", new Dimension(125,0), new Dimension(0, 100), new Dimension(125,0), new Dimension(0, 100), page03_shopping, BorderLayout.CENTER);
			return;
		}
// confirm a customer order checkout
		if (e.getSource() == page03_checkout.confirmButton)
		{
			java.util.Date today = new java.util.Date();
			java.sql.Date sqlToday = new java.sql.Date(today.getTime()); // current date

			String date = page03_checkout.creditCardExpiryField.getText(); // expiry date of card
			OnlineReceipt tempReceipt;
			try {
				tempReceipt = tm.customerCheckOut(page03_shopping.cid, sqlToday, page03_checkout.bill, page03_checkout.creditCardNumberField.getText(), java.sql.Date.valueOf(date));
				
				JOptionPane.showMessageDialog(this, "Purchase Successful, estimated days for delivery: " + tempReceipt.getNumDays());
				this.actionPerformed(new ActionEvent(page03_checkout.returnButton, getDefaultCloseOperation(), ""));
				this.actionPerformed(new ActionEvent(page03_shopping.logoutButton, getDefaultCloseOperation(), ""));
			}
			catch (IllegalArgumentException e1)
			{
				JOptionPane.showMessageDialog(this, "Invalid Date Format");
			}
			catch (SQLException e1) {
				JOptionPane.showMessageDialog(this, e1.getMessage());
			}
			return;
		}
// goes to add supplier page of manager
		if (e.getSource() == page04_manager.addSupplierButton)
		{ 
			this.goToPage(true, "Add Supplier", new Dimension(340, 0), new Dimension(0, 130), new Dimension(75, 0), new Dimension(0, 75), page04_addSupplier, BorderLayout.CENTER);
			return;
		}
// goes to remove supplier page of manager
		if (e.getSource() == page04_manager.removeSupplierButton)
		{ 
			this.goToPage(true, "Remove Supplier", new Dimension(340, 0), new Dimension(0, 130), new Dimension(75, 0), new Dimension(0,75), page04_removeSupplier, BorderLayout.CENTER);
			return;
		}
// goes to process shipment page of manager
		if (e.getSource() == page04_manager.processShipmentButton)
		{ 
			this.goToPage(true, "Process Shipment", new Dimension(150,0), new Dimension(0,75), new Dimension(150,0), new Dimension(0,75), page04_processShipment, BorderLayout.CENTER);
			return;
		}
// goes to process order page of manager
		if (e.getSource() == page04_manager.processOrderButton)
		{ 
			this.goToPage(true, "Process Orders", new Dimension(150,0), new Dimension(0,75), new Dimension(150,0), new Dimension(0,75), page04_processOrders, BorderLayout.CENTER);
			return;
		}
// goes to daily sales report page of manager
		if (e.getSource() == page04_manager.dailySalesReportButton)
		{
			try {
				page04_dailySalesReport.storeOptions = tm.clerkGetStoreNames();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			page04_dailySalesReport.resetPage();
			this.goToPage(true, "Daily Sales Report", new Dimension(150,0), new Dimension(0,75), new Dimension(150,0), new Dimension(0,75), page04_dailySalesReport, BorderLayout.CENTER);
			page04_dailySalesReport.storeList.addActionListener(this);
			return;
		}
// goes to top selling items page of manager
		if (e.getSource() == page04_manager.topSellingItemsButton)
		{ 
			this.goToPage(true, "Top Selling Items", new Dimension(150, 0), new Dimension(0, 50), new Dimension(150, 0), new Dimension(0, 50), page04_topSellingItems, BorderLayout.CENTER);
			return;
		}

// goes back to the manager page
		if (e.getSource() == page04_processShipment.returnButton || e.getSource() == page04_addSupplier.returnButton || 
				e.getSource() == page04_removeSupplier.returnButton || e.getSource() == page04_processOrders.returnButton || e.getSource() == page04_dailySalesReport.returnButton || e.getSource() == page04_topSellingItems.returnButton)
		{ 
			this.goToPage(false, "", new Dimension(350,0), new Dimension(0, 125), null, null, page04_manager, BorderLayout.CENTER);
			return;
		}
// manager adds a supplier
		if (e.getSource() == page04_addSupplier.submitButton)
		{ 
			String nameText = (String) page04_addSupplier.supplierNameField.getText();
			String addressText = (String) page04_addSupplier.addressField.getText();
			String cityText = (String) page04_addSupplier.cityField.getText();
			String statusText = (String) page04_addSupplier.statusField.getText();
		    try {
				tm.managerAddSupplier(nameText, addressText, cityText, statusText);
			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(this, e1.getMessage());
				return;
			}
			JOptionPane.showMessageDialog(this, "Supplier Added!");
			page04_addSupplier.supplierNameField.setText("");
			page04_addSupplier.addressField.setText("");
			page04_addSupplier.cityField.setText("");
			page04_addSupplier.statusField.setText("");
			this.actionPerformed(new ActionEvent(page04_addSupplier.returnButton, getDefaultCloseOperation(), ""));
			return;
		}
// manager removes a supplier
		if (e.getSource() == page04_removeSupplier.submitButton)
		{ 
			String nameText = (String) page04_removeSupplier.supplierNameField.getText();
		    try {
				tm.managerRemoveSupplier(nameText);
			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(this, e1.getMessage());
				return;
			}
			JOptionPane.showMessageDialog(this, "Supplier Removed!");
			page04_removeSupplier.supplierNameField.setText("");
			this.actionPerformed(new ActionEvent(page04_removeSupplier.returnButton, getDefaultCloseOperation(), ""));
			return;
		}
// manager processes a shipment
		if (e.getSource() == page04_processShipment.processButton)
		{ 
			String IDText = (String) page04_processShipment.shipmentIDField.getText();
			int sid;
		    try
		    {
		      sid = Integer.parseInt(IDText.trim());
		    }
		    catch (NumberFormatException nfe)
		    {
		    	JOptionPane.showMessageDialog(this, "sID not a number");
		    	page04_processShipment.processButton.setEnabled(false);
		    	return;
		    }
		    try {
				tm.managerProcessShipment(sid);
			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(this, e1.getMessage());
				return;
			}
			JOptionPane.showMessageDialog(this, "Shipment Processed!");
			page04_processShipment.shipmentIDField.setText("");
			page04_processShipment.populateTable(null, null);
			page04_processShipment.processButton.setEnabled(false);
			this.actionPerformed(new ActionEvent(page04_processShipment.returnButton, getDefaultCloseOperation(), ""));
			return;
		}
// manager processes an order
		if (e.getSource() == page04_processOrders.processButton)
		{ 
			try
			{
				String expectedDateString = page04_processOrders.expectedDeliveryDateField.getText();
				String currentDateString = page04_processOrders.currentDateField.getText();
		    
				Date expectedDate = Date.valueOf(expectedDateString);
				Date currentDate = Date.valueOf(currentDateString);
				
				tm.managerProcessOrderDeliveries(expectedDate, currentDate);
				
				JOptionPane.showMessageDialog(this, "Orders Processed!");
				page04_processOrders.expectedDeliveryDateField.setText("");
				page04_processOrders.currentDateField.setText("");				
				this.actionPerformed(new ActionEvent(page04_processOrders.returnButton, getDefaultCloseOperation(), ""));
		    }
		    catch (IllegalArgumentException e1)
		    {
		    	JOptionPane.showMessageDialog(this, "Invalid date format");		    	
		    }
		    catch (Exception e1)
		    {
		    	JOptionPane.showMessageDialog(this, e1.getMessage());		    	
		    }
		  
			return;
		}
// manager changes store on daily sales report
		if (e.getSource() == page04_dailySalesReport.storeList)
		{ 
			this.tryDailySalesReport();
		}
// generate a list of the top selling items
		if (e.getSource() == page04_topSellingItems.submitButton)
		{ 
			String date = page04_topSellingItems.dateField.getText();
			String numItemsText = (String) page04_topSellingItems.numItemsField.getText();
			int numItems;
			List<TopSellingItem> topSellers;
			
		    try
		    {
		      numItems = Integer.parseInt(numItemsText.trim());
		    }
		    catch (NumberFormatException nfe)
		    {
		    	return;
		    }
			try {
				topSellers = tm.managerGetTopSellingItems(java.sql.Date.valueOf(date), numItems);
			}
			catch (IllegalArgumentException e1)
			{
				JOptionPane.showMessageDialog(this, "Invalid Date Format");
				return;
			}
			catch (SQLException e1) {
				JOptionPane.showMessageDialog(this, e1.getMessage());
				return;
			}
			
			Object[] columnNames = {"Title", "Company", "Copies Sold", "Stock Left"};
			
			if(!topSellers.isEmpty())
			{
				Object[][] data = new Object[topSellers.size()][];
				for (int i = 0; i < topSellers.size(); i++)
				{
					data[i] = new Object[4];
					data[i][0] = topSellers.get(i).getTitle();
					data[i][1] = topSellers.get(i).getCompany();
					data[i][2] = topSellers.get(i).getStockLeft(); // needs change
					data[i][3] = topSellers.get(i).getCopiesSold(); // should be copies sold
				}
				this.invalidate();
				page04_topSellingItems.populateTable(columnNames, data);
				this.validate();
				this.repaint();
			}
			else
			{
				this.invalidate();
				page04_topSellingItems.populateTable(null, null);
				this.validate();
				this.repaint();
			}
			return;
			
		}

// go back to admin page
		if (e.getSource() == page05_displayTables.returnButton || e.getSource() == page05_insertToTable.returnButton || e.getSource() == page05_deleteFromTable.returnButton)
		{ 
			this.goToPage(false, "", new Dimension(350,0), new Dimension(0, 125), null, null, page05_admin, BorderLayout.CENTER);
			return;
		}
// should create all tables
		if (e.getSource() == page05_admin.createTablesButton)
		{ 
			try {
				tm.createTables();
				JOptionPane.showMessageDialog(this, "Creation Successful");
			} catch (Exception r) {
				JOptionPane.showMessageDialog(this, r.getMessage());
			}			
			
			return;
		}
// should drop all tables
		if (e.getSource() == page05_admin.dropTablesButton)
		{
			try {
				tm.dropTables();
				JOptionPane.showMessageDialog(this, "Drop Successful");
			} catch (Exception r) {
				JOptionPane.showMessageDialog(this, r.getMessage());
			}		
			
			return;
		}
// should populate all tables
		if (e.getSource() == page05_admin.populateTablesButton)
		{ 
			try
			{
				tm.populateTables();
				JOptionPane.showMessageDialog(this, "Tables Populated");
			}
			catch (Exception r)
			{
				JOptionPane.showMessageDialog(this, r.getMessage());
			}
						
			return;
		}
// goes to insert to table page
		if (e.getSource() == page05_admin.insertToTableButton)
		{ 
			this.goToPage(true, "Insert to Table", new Dimension(320, 0), new Dimension(0, 15), new Dimension(75, 0), new Dimension(0, 15), page05_insertToTable, BorderLayout.CENTER);
			return;
		}
// goes to delete from table page
		if (e.getSource() == page05_admin.deleteFromTableButton)
		{
			this.goToPage(true, "Delete from Table", new Dimension(320, 0), new Dimension(0, 125), new Dimension(75, 0), new Dimension(0, 15), page05_deleteFromTable, BorderLayout.CENTER);
			return;
		}
// go to display table page
		if (e.getSource() == page05_admin.displayTableButton)
		{ 
			this.goToPage(true, "Table Display", new Dimension(150,0), new Dimension(0, 50), new Dimension(150, 0), new Dimension(0, 50), page05_displayTables, BorderLayout.CENTER);
			this.actionPerformed(new ActionEvent(page05_displayTables.tableList, getDefaultCloseOperation(), ""));
			return;
		}
// refresh contents of admin's table
		if (e.getSource() == page05_displayTables.tableList)
		{ 
			this.invalidate();
			List<List<String>> currentTable;
			String errorMessage = "Error with displaying";
			try {
				currentTable = tm.display(TableEnum.valueOf(page05_displayTables.tableOptions.get(page05_displayTables.tableList.getSelectedIndex())));
			} catch (Exception r) {
				currentTable = null;
				errorMessage = r.getMessage();
			}
			if (currentTable == null)
			{
				JOptionPane.showMessageDialog(this, errorMessage);
				return;
			}
			Object[] columnNames = currentTable.get(0).toArray();
			Object[][] data = new Object[currentTable.size()][];
			for (int i = 0; i < currentTable.size(); i++)
			{
				data[i] = currentTable.get(i).toArray();
			}
			data = Arrays.copyOfRange(data, 1, data.length);
			page05_displayTables.populateTable(columnNames, data);
			this.validate();
			this.repaint();
			return;
		}
// repopulates list of fields to insert into a table
		if (e.getSource() == page05_insertToTable.tableList)
		{ 
			this.invalidate();
			page05_insertToTable.rePopulateFields();
			page05_insertToTable.insertButton.addActionListener(this);
			this.validate();
			this.repaint();
			return;
		}
// inserts into a table
		if (e.getSource() == page05_insertToTable.insertButton)
		{ 
			TableEnum tEnum = TableEnum.valueOf(page05_insertToTable.tableOptions.get(page05_insertToTable.tableList.getSelectedIndex()));
			
			// Add to string list and also make sure they have filled all primary key fields
			List<String> insertVals = new ArrayList<String>();
			for (int i = 0; i < page05_insertToTable.entryFields.size(); i++)
			{
				String currentFieldText = page05_insertToTable.entryFields.get(i).getText();
				if (currentFieldText.equals(""))
				{ // the text is blank
					JOptionPane.showMessageDialog(this, "Please enter values for all fields");
					return;
				}
				insertVals.add(currentFieldText);
			}
			try {
				tm.insert(tEnum, insertVals);
				JOptionPane.showMessageDialog(this, "Insertion successful");
				this.actionPerformed(new ActionEvent(page05_insertToTable.returnButton, getDefaultCloseOperation(), ""));
			} catch (Exception r) {
				JOptionPane.showMessageDialog(this, r.getMessage());
			}
			
			return;
		}
// re populates fields on delete page
		if (e.getSource() == page05_deleteFromTable.tableList)
		{ 
			this.invalidate();
			page05_deleteFromTable.rePopulateFields();
			page05_deleteFromTable.deleteButton.addActionListener(this);
			this.validate();
			this.repaint();
			return;
		}
// deletes a row (using a key) from a table
		if (e.getSource() == page05_deleteFromTable.deleteButton)
		{ 
			TableEnum tEnum = TableEnum.valueOf(page05_deleteFromTable.tableOptions.get(page05_deleteFromTable.tableList.getSelectedIndex()));
			
			// Add to string list and also make sure they have filled all primary key fields
			List<String> deleteKeys = new ArrayList<String>();
			for (int i = 0; i < page05_deleteFromTable.entryFields.size(); i++)
			{
				String currentFieldText = page05_deleteFromTable.entryFields.get(i).getText();
				if (currentFieldText.equals(""))
				{ // the text is blank
					JOptionPane.showMessageDialog(this, "Please enter values for all fields");
					return;
				}
				deleteKeys.add(currentFieldText);
			}
			try {
				tm.delete(tEnum, deleteKeys);
				JOptionPane.showMessageDialog(this, "Deletion successful");
				this.actionPerformed(new ActionEvent(page05_deleteFromTable.returnButton, getDefaultCloseOperation(), ""));
			
			} catch (Exception r) {
				JOptionPane.showMessageDialog(this, r.getMessage());
			}
			
			return;
		}
	}
	
	/** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e)
    {
    	
    }
    
    @Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyReleased(KeyEvent e) {
// clerk types into upcfield, try and find the item and also enable additembutton if found
		if (e.getSource() == page02_processPurchase.UPCField)
    	{
			String fieldText = page02_processPurchase.UPCField.getText();
			List<List<String>> itemTable;
			try {
				itemTable = tm.display(TableEnum.Item);
			} catch (Exception r) {
				page02_processPurchase.foundItemLabel.setText("");
				page02_processPurchase.addItemButton.setEnabled(false);
				return;
			}
			// go through every upc and try and find this item (a bit hacky atm)
			// first convert to normal arrays
			Object[] columnNames = itemTable.get(0).toArray();
			Object[][] data = new Object[itemTable.size()][];
			for (int i = 0; i < itemTable.size(); i++)
			{
				data[i] = itemTable.get(i).toArray();
			}
			int upcCol = -1;
			int titleCol = -1;
			for (int i = 0; i < columnNames.length; i++) // go through each column name
			{
				if (columnNames[i].toString().equals("UPC")) // find column that is UPC
				{
					upcCol = i;
				}
				if (columnNames[i].toString().equals("TITLE")) // find column that is title
				{
					titleCol = i;
				}
			}
			if (upcCol == -1 || titleCol == -1) // didn't find one or both
			{
				page02_processPurchase.foundItemLabel.setText("");
				page02_processPurchase.addItemButton.setEnabled(false);
				return;
			}
			for (int j = 0; j < itemTable.size(); j++) // go through every row of this column
			{
				String currUPC = data[j][upcCol].toString(); // get [row][col] of data as string
				if (currUPC.equals(fieldText)) // check if we have a match
				{
					page02_processPurchase.foundItemLabel.setText(data[j][titleCol].toString());
					page02_processPurchase.addItemButton.setEnabled(true);
					return;
				}
			}
			page02_processPurchase.foundItemLabel.setText("");
			page02_processPurchase.addItemButton.setEnabled(false);
			return;
    	}
// search for return items
		if (e.getSource() == page02_processReturn.receiptIDField || e.getSource() == page02_processReturn.itemUPCField)
		{
			String receiptIDText = page02_processReturn.receiptIDField.getText();
			String upcFieldText = page02_processReturn.itemUPCField.getText();
			List<List<String>> purchaseItemTable;
			try {
				purchaseItemTable = tm.display(TableEnum.PurchaseItem);
			} catch (Exception r) {
				page02_processReturn.resultLabel.setText("");
				page02_processReturn.returnItemButton.setEnabled(false);
				return;
			}
			// go through every upc/receiptid and try and find this item (a bit hacky atm)
			// first convert to normal arrays
			Object[] columnNames = purchaseItemTable.get(0).toArray();
			Object[][] data = new Object[purchaseItemTable.size()][];
			for (int i = 0; i < purchaseItemTable.size(); i++)
			{
				data[i] = purchaseItemTable.get(i).toArray();
			}
			int receiptIDCol = -1;
			int upcCol = -1;
			for (int i = 0; i < columnNames.length; i++) // go through each column name
			{
				if (columnNames[i].toString().equals("RECEIPTID")) // find column that is receipt id
				{
					receiptIDCol = i;
				}
				if (columnNames[i].toString().equals("UPC")) // find column that is UPC
				{
					upcCol = i;
				}
			}
			if (receiptIDCol == -1 || upcCol == -1) // didn't find one or both
			{
				page02_processReturn.resultLabel.setText("");
				page02_processReturn.returnItemButton.setEnabled(false);
				return;
			}
			for (int j = 0; j < purchaseItemTable.size(); j++) // go through every row of this column
			{
				String currReceiptID = data[j][receiptIDCol].toString(); // get [row][col] of data as string
				String currUPC = data[j][upcCol].toString(); // get [row][col] of data as string
				if (currUPC.equals(upcFieldText) && currReceiptID.equals(receiptIDText)) // check if we have a match
				{
					page02_processReturn.resultLabel.setText("Item Found");
					page02_processReturn.returnItemButton.setEnabled(true);
					return;
				}
			}
			page02_processReturn.resultLabel.setText("");
			page02_processReturn.returnItemButton.setEnabled(false);
			return;
		}
// manager types into sID field on shipment processing
		if (e.getSource() == page04_processShipment.shipmentIDField)
		{ 
			List<ShipItem> theItems;
			String IDText = (String) page04_processShipment.shipmentIDField.getText();
			int sid;
		    try
		    {
		      sid = Integer.parseInt(IDText.trim());
		    }
		    catch (NumberFormatException nfe)
		    {
		    	page04_processShipment.processButton.setEnabled(false);
		    	return;
		    }
			try {
				theItems = tm.managerGetItemsInShipment(sid);
			} catch (SQLException e1) {
		    	page04_processShipment.processButton.setEnabled(false);
				return;
			}
			Object[] columnNames = tm.getTableColumnNames(TableEnum.ShipItem).toArray();
			
			if(!theItems.isEmpty())
			{
				Object[][] data = new Object[theItems.size()][];
				for (int i = 0; i < theItems.size(); i++)
				{
					data[i] = new Object[4];
					data[i][0] = theItems.get(i).getSid();
					data[i][1] = theItems.get(i).getUpc();
					data[i][2] = theItems.get(i).getSupPrice();
					data[i][3] = theItems.get(i).getQuantity();
				}
				this.invalidate();
				page04_processShipment.populateTable(columnNames, data);
				page04_processShipment.processButton.setEnabled(true);
				this.validate();
				this.repaint();
			}
			else
			{
				this.invalidate();
				page04_processShipment.populateTable(null, null);
				page04_processShipment.processButton.setEnabled(false);
				this.validate();
				this.repaint();
			}
			return;
		}
// next 2 are for shopping search
		if (e.getSource() == page03_shopping.itemTitleField)
		{
			this.searchItems();
		}
		if (e.getSource() == page03_shopping.leadSingerField)
		{
			this.searchItems();
		}
// manager typing into remove supplier field
		if (e.getSource() == page04_removeSupplier.supplierNameField)
		{
			
		}
// manager typing into daily sales report date field
		if (e.getSource() == page04_dailySalesReport.dateField)
		{
			this.tryDailySalesReport();
		}
	}
	
	// on the fly searching of items as the user types (for shopping customers)
	// will need to repopulate shopping page's table
	private void searchItems()
	{
		try 
        {
                Set<Item> availableItems = tm.customerItemSearch(page03_shopping.categoryList.getSelectedItem().toString(), page03_shopping.itemTitleField.getText(), page03_shopping.leadSingerField.getText());

                Object[] columnNames = tm.getTableColumnNames(TableEnum.Item).toArray();
                if(!availableItems.isEmpty())
                {
                        Object[][] data = new Object[availableItems.size()][];
                        int count = 0;
                        Iterator<Item> it = availableItems.iterator();
                        while (it.hasNext()) {
                
                                // Get element
                                Item element = it.next();
                                data[count] = new Object[7];
                                data[count][0] = element.getUpc();
                                data[count][1] = element.getTitle();
                                data[count][2] = element.getType();
                                data[count][3] = element.getCategory();
                                data[count][4] = element.getCompany();
                                data[count][5] = element.getYear();
                                data[count][6] = element.getSellPrice();
                                count++;
                        }
                        
                        this.invalidate();
                        page03_shopping.populateTable(columnNames, data);
                        page03_shopping.table.getSelectionModel().setSelectionInterval(0, 0);
                        page03_shopping.addToCartButton.setEnabled(true);
                        this.validate();
                        this.repaint();
                }
                else
                {
                        this.invalidate();
                        page03_shopping.populateTable(null, null);
                        page03_shopping.addToCartButton.setEnabled(false);
                        this.validate();
                        this.repaint();                 
                }
        }
        catch (SQLException e) 
        {
                JOptionPane.showMessageDialog(this, e.getMessage());
        }                       
        return;
	}
	
	private void tryDailySalesReport()
	{
		String date = page04_dailySalesReport.dateField.getText();
		List<SalesReportItem> salesItems;
		try {
			salesItems = tm.managerGetDailySalesReport(page04_dailySalesReport.storeList.getSelectedItem().toString(), java.sql.Date.valueOf(date));
		}
		catch (IllegalArgumentException e1)
		{
			return;
		}
		catch (SQLException e1) {
			JOptionPane.showMessageDialog(this, e1.getMessage());
			return;
		}
		 Object[] columnNames = {"UPC", "Category", "Unit Price", "Units", "Total Value"};
         if(!salesItems.isEmpty())
         {
                 Object[][] data = new Object[salesItems.size()+Item.Category.values().length+1][5]; // add for num categories just to be ready for totals
                 String currentCategory = salesItems.get(0).getCategory();
                 int offset = 0;
                 float thisCatPrice = 0.0f;
                 int thisCatItems = 0;
                 float totalPrice = 0.0f;
                 int totalItems = 0;
                 for (int i = 0; i < salesItems.size()+1; i++)
                 {
                	 if (i == salesItems.size()) // last index, add to array the extra totals line
                	 {
                		 // do last total for category
                		 data[i+offset][0] = "";
                		 data[i+offset][1] = "Total";
                		 data[i+offset][2] = "";
                		 data[i+offset][3] = thisCatItems;
                		 data[i+offset][4] = thisCatPrice;
                		 
                		 // final total
                		 data[i+offset+1][0] = "";
                		 data[i+offset+1][1] = "Total Daily";
                		 data[i+offset+1][2] = "Sales";
                		 data[i+offset+1][3] = totalItems;
                		 data[i+offset+1][4] = totalPrice;
                		 break;
                	 }
                	 data[i+offset] = new Object[5];
                	 SalesReportItem tempItem = salesItems.get(i);
                	 if (tempItem.getCategory().equals(currentCategory)) // same category, do basic stuff
                	 {
                		 data[i+offset][0] = tempItem.getUpc();
                		 data[i+offset][1] = tempItem.getCategory();
                		 data[i+offset][2] = tempItem.getUnitPrice();
                		 data[i+offset][3] = tempItem.getUnits();
                		 data[i+offset][4] = tempItem.getTotalValue();
                		 thisCatPrice += tempItem.getTotalValue();
                		 totalPrice += tempItem.getTotalValue();
                		 thisCatItems += tempItem.getUnits();
                		 totalItems += tempItem.getUnits();
                	 }
                	 else // new category group now, need to print total to array and reset category vars
                	 {
                		 data[i+offset][0] = "";
                		 data[i+offset][1] = "Total";
                		 data[i+offset][2] = "";
                		 data[i+offset][3] = thisCatItems;
                		 data[i+offset][4] = thisCatPrice;
                		 thisCatItems = 0;
                		 thisCatPrice = 0.0f;
                		 currentCategory = tempItem.getCategory();
                		 offset++;
                		 i--; // revert to catch this current item on next run since we technically skipped it
                	 }
                 }
                 this.invalidate();
                 page04_dailySalesReport.populateTable(columnNames, data);
                 this.validate();
                 this.repaint();
         }
         else
         {
                 this.invalidate();
                 page04_dailySalesReport.populateTable(null, null);
                 this.validate();
                 this.repaint();                 
         }
		return;
	}
	
	private void goToPage(boolean pushingToThisView, String navBarText, Dimension leftBorderDimensions, Dimension topBorderDimensions, Dimension rightBorderDimensions, Dimension bottomBorderDimensions, JPanel pageToAdd, String layout)
	{
		this.invalidate();
		getContentPane().removeAll();
		// to center the actual view
		if (leftBorderDimensions != null)
			getContentPane().add(Box.createRigidArea(new Dimension(leftBorderDimensions.width,leftBorderDimensions.height)), BorderLayout.WEST);
		if (topBorderDimensions != null)
			getContentPane().add(Box.createRigidArea(new Dimension(topBorderDimensions.width,topBorderDimensions.height)), BorderLayout.PAGE_START);
		if (rightBorderDimensions != null)
			getContentPane().add(Box.createRigidArea(new Dimension(rightBorderDimensions.width,rightBorderDimensions.height)), BorderLayout.EAST);
		if (bottomBorderDimensions != null)
			getContentPane().add(Box.createRigidArea(new Dimension(bottomBorderDimensions.width,bottomBorderDimensions.height)), BorderLayout.PAGE_END);
		// add the new view
	    getContentPane().add(pageToAdd, layout);
		// update nav bar
	    if (pushingToThisView)
	    	this.pushNavBarButton(navBarText);
	    else
	    	this.popNavBarButton();
		this.validate();
		this.repaint();
	}
	
	// add a button to the nav bar
	private void pushNavBarButton(String title)
	{
		// add arrow label
		JLabel arrow = new JLabel(">");
		arrow.setForeground(Color.gray);
		navBarArrows.add(arrow);
		navBar.add(arrow);
		
		Integer navButtonCount = this.navBarButtons.size();
		JButton button = new JButton(title);
		button.setForeground(Color.white);
		button.setBackground(Color.lightGray);
		button.setFont(new Font("Century Gothic", Font.BOLD, 11));
		button.setEnabled(false);
		navBarButtons.add(button);
		navBar.add(button);
	}
	
	private void popNavBarButton()
	{
		Integer index = navBarArrows.size()-1;
		if (index <= 0)
			return;
		navBar.remove(navBar.getComponentCount()-1);
		navBar.remove(navBar.getComponentCount()-1);
		
		//navBar.remove((Component) (navBarArrows.get(index)));
		navBarArrows.remove(index);
		
		//navBar.remove((Component) (navBarButtons.get(index)));
		navBarButtons.remove(index);
	}
	
	// most buttons will have this style on AMS Store
	public static JButton makeGrayWhiteButton(String text, float alignment)
	{
		JButton tempButton = new JButton(text);
		tempButton.setAlignmentX(alignment);
		tempButton.setForeground(Color.gray);
		tempButton.setBackground(Color.white);
		tempButton.setFont(new Font("Century Gothic", Font.BOLD, 12));
		return tempButton;
	}
	
	public static JLabel makeLeftAlignedGrayLabel(String text, Integer fontSize)
	{
		JLabel tempLabel = new JLabel(text, JLabel.LEFT);
		tempLabel.setVerticalTextPosition(JLabel.CENTER);
		
		tempLabel.setHorizontalTextPosition(JLabel.CENTER);
		tempLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
		tempLabel.setFont(new Font("Century Gothic", Font.PLAIN, fontSize));
		tempLabel.setForeground(Color.gray);
		return tempLabel;
	}
	
	public static JTextField makeLeftGrayTextField (String text, Integer width)
	{
		JTextField tempField = new JTextField(text);
		tempField.setAlignmentX(Component.LEFT_ALIGNMENT);
		tempField.setForeground(Color.gray);
		tempField.setBackground(Color.white);
		tempField.setFont(new Font("Century Gothic", Font.BOLD, 11));
		tempField.setMaximumSize(new Dimension(width,20));
		return tempField;
	}
	
	public static JFormattedTextField makeLeftGrayIntegerTextField (Integer initialValue, Integer width)
	{
		NumberFormat numFormat;
		numFormat = NumberFormat.getNumberInstance();
		JFormattedTextField tempField = new JFormattedTextField("");
		//if (initialValue != -1)
		//	tempField.setValue(new Integer(initialValue));
		if (initialValue != 0)
			tempField.setText(initialValue.toString());
		tempField.setAlignmentX(Component.LEFT_ALIGNMENT);
		tempField.setForeground(Color.gray);
		tempField.setBackground(Color.white);
		tempField.setFont(new Font("Century Gothic", Font.BOLD, 11));
		tempField.setMaximumSize(new Dimension(width,20));
		return tempField;
	}
	
	public static JPasswordField makeLeftGrayPassField (Integer width)
	{
		JPasswordField tempField = new JPasswordField();
		tempField.setAlignmentX(Component.LEFT_ALIGNMENT);
		tempField.setForeground(Color.gray);
		tempField.setBackground(Color.white);
		tempField.setFont(new Font("Century Gothic", Font.BOLD, 11));
		tempField.setMaximumSize(new Dimension(width,20));
		return tempField;
	}
}
